/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.github.florent37.camerafragment.sample.slice;

import static ohos.security.SystemPermission.CAMERA;
import static ohos.security.SystemPermission.MICROPHONE;
import static ohos.security.SystemPermission.READ_USER_STORAGE;
import static ohos.security.SystemPermission.WRITE_USER_STORAGE;

import com.github.florent37.camerafragment.CameraFraction;
import com.github.florent37.camerafragment.CameraFractionApi;
import com.github.florent37.camerafragment.configuration.Configuration;
import com.github.florent37.camerafragment.internal.ui.BaseAnncaFraction;
import com.github.florent37.camerafragment.internal.utils.Toast;
import com.github.florent37.camerafragment.listeners.CameraFragmentResultListener;
import com.github.florent37.camerafragment.listeners.CameraFragmentStateListener;
import com.github.florent37.camerafragment.sample.CameraFragmentAbility;
import com.github.florent37.camerafragment.sample.ResourceTable;
import com.github.florent37.camerafragment.sample.bean.RxBusEvent;
import com.github.florent37.camerafragment.sample.rxbus.RxBus;
import com.github.florent37.camerafragment.sample.rxbus.Subscribe;
import com.github.florent37.camerafragment.sample.rxbus.ThreadMode;

import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.fraction.Fraction;
import ohos.aafwk.ability.fraction.FractionManager;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.bundle.IBundleManager;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * 另一个相机页面布局
 *
 * @since 2021-03-17
 */
public class CameraFragmentAbilityCustomsSlice extends AbilitySlice implements Component.ClickedListener {
    private static final int REQUEST_CAMERA_PERMISSIONS = 931;
    private static final int REQUEST_PREVIEW_CODE = 1001;
    private static final int ACTION_CONFIRM = 900;
    private static final int ACTION_RETAKE = 901;
    private static final int ACTION_CANCEL = 902;
    private static final String RESPONSE_CODE_ARG = "response_code_arg";
    private static final String FRAGMENT_TAG = "camera";
    private Component cameraLayout;
    private Component addCameraButton;
    private Button mediaActionSwitchView;
    private Button recordButton;
    private Button cameraSwitchView;
    private Button flashSwitchView;
    private Button settingsView;
    private EventHandler eventHandler = new EventHandler(EventRunner.create());

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_camerafragment_ability_main_customs);
        RxBus.get(this).register(this); // 注册RxBus
        settingsView = (Button) findComponentById(ResourceTable.Id_settings_view);
        flashSwitchView = (Button) findComponentById(ResourceTable.Id_flash_switch_view);
        cameraSwitchView = (Button) findComponentById(ResourceTable.Id_front_back_camera_switcher);
        recordButton = (Button) findComponentById(ResourceTable.Id_record_button);
        mediaActionSwitchView = (Button) findComponentById(ResourceTable.Id_photo_video_camera_switcher);
        cameraLayout = findComponentById(ResourceTable.Id_cameraLayout);
        addCameraButton = findComponentById(ResourceTable.Id_addCameraButton);

        recordButton.setClickedListener(this);
        settingsView.setClickedListener(this);
        addCameraButton.setClickedListener(this);
        flashSwitchView.setClickedListener(this);
        cameraSwitchView.setClickedListener(this);
        mediaActionSwitchView.setClickedListener(this);
    }

    @Override
    public void onClick(Component component) {
        switch (component.getId()) {
            case ResourceTable.Id_settings_view:
                CameraFractionApi cameraFractionSettings = getCameraFragment();
                if (cameraFractionSettings != null) {
                    cameraFractionSettings.openSettingDialog();
                }
                break;
            case ResourceTable.Id_flash_switch_view:
                CameraFractionApi cameraFractionFlashSwitch = getCameraFragment();
                if (cameraFractionFlashSwitch != null) {
                    cameraFractionFlashSwitch.toggleFlashMode();
                }
                break;
            case ResourceTable.Id_front_back_camera_switcher:
                CameraFractionApi cameraFractionFrontBack = getCameraFragment();
                if (cameraFractionFrontBack != null) {
                    cameraFractionFrontBack.switchCameraTypeFrontBack();
                }
                break;
            case ResourceTable.Id_record_button:
                takePhotoOrRecordVideo();
                break;
            case ResourceTable.Id_photo_video_camera_switcher:
                final CameraFractionApi cameraFractionPhotoVideo = getCameraFragment();
                if (cameraFractionPhotoVideo != null) {
                    cameraFractionPhotoVideo.switchActionPhotoVideo();
                }
                break;
            case ResourceTable.Id_addCameraButton:
                requestPermissionsAndOpenCamera();
                break;
            default:
                break;
        }
    }

    private void takePhotoOrRecordVideo() { // 开始拍照和录像
        CameraFractionApi cameraFractionRecord = getCameraFragment();
        if (cameraFractionRecord != null) {
            cameraFractionRecord.takePhotoOrCaptureVideo(new CameraFragmentResultListener() {
                @Override
                public void onVideoRecorded(String filePath) {
                }

                @Override
                public void onPhotoTaken(String filePath) {
                }
            }, getExternalFilesDir("").getAbsolutePath(), null);
        }
    }

    private void requestPermissionsAndOpenCamera() { // 请求权限并打开相机
        // 权限申请
        List<String> permissionsToRequest = new ArrayList<>();
        String[] permissions = new String[]{CAMERA, MICROPHONE, WRITE_USER_STORAGE, READ_USER_STORAGE};
        for (String permission : permissions) {
            if (verifyCallingPermission(permission) != IBundleManager.PERMISSION_GRANTED) {
                // 应用未被授予权限
                if (canRequestPermission(permission)) { // 是否可以申请弹框授权 如果可以就把权限添加到列表中
                    permissionsToRequest.add(permission);
                }
            }
        }
        if (!permissionsToRequest.isEmpty()) { // 发送事件
            RxBusEvent busData = new RxBusEvent();
            busData.setAbility(this);
            RxBus.get(this).send(busData);
            requestPermissionsFromUser(permissions, REQUEST_CAMERA_PERMISSIONS); // 说明有权限没有申请
        } else {
            // 开启相机
            addCamera();
        }
    }

    /**
     * 添加相机页面
     */
    public void addCamera() {
        addCameraButton.setVisibility(Component.HIDE);
        cameraLayout.setVisibility(Component.VISIBLE);

        Configuration.Builder builder = new Configuration.Builder();
        builder.setCamera(Configuration.CAMERA_FACE_FRONT)
            .setFlashMode(Configuration.FLASH_MODE_ON)
            .setMediaAction(Configuration.MEDIA_ACTION_VIDEO);

        CameraFraction cameraFraction = CameraFraction.newInstance(builder.build());
        FractionManager fractionManager = ((CameraFragmentAbility) getAbility()).getFractionManager();
        fractionManager
            .startFractionScheduler()
            .add(ResourceTable.Id_content, cameraFraction, FRAGMENT_TAG)
            .submit();
        if (cameraFraction != null) {
            cameraFraction.setResultListener(new CameraFragmentResult());

            cameraFraction.setStateListener(new CameraFragmentState());
        }
    }

    private CameraFractionApi getCameraFragment() {
        FractionManager fractionManager = ((CameraFragmentAbility) getAbility()).getFractionManager();
        Optional<Fraction> fractionByTag = fractionManager.getFractionByTag(FRAGMENT_TAG);
        if (fractionByTag.isPresent()) {
            return (CameraFractionApi) fractionByTag.get();
        } else {
            return new BaseAnncaFraction();
        }
    }

    /**
     * 相机结果回调
     *
     * @since 2021-04-10
     */
    private class CameraFragmentResult implements CameraFragmentResultListener {
        @Override
        public void onVideoRecorded(String filePath) {
            // 视频录制完,不跳转页面,直接弹出吐司提示
            Toast.show(getContext(), filePath);
        }

        @Override
        public void onPhotoTaken(String filePath) {
            Intent intent = PreviewAbilitySlice.newIntentPhoto(CameraFragmentAbilityCustomsSlice.this, filePath);
            startAbilityForResult(intent, REQUEST_PREVIEW_CODE);
        }
    }

    /**
     * 相机状态回调
     *
     * @since 2021-04-10
     */
    private class CameraFragmentState implements CameraFragmentStateListener {
        @Override
        public void onCurrentCameraBack() {
            cameraSwitchView.setText("BACK");
        }

        @Override
        public void onCurrentCameraFront() {
            cameraSwitchView.setText("FRONT");
        }

        @Override
        public void onFlashAuto() {
            flashSwitchView.setText("AUTO");
        }

        @Override
        public void onFlashOn() {
            flashSwitchView.setText("ON");
        }

        @Override
        public void onFlashOff() {
            flashSwitchView.setText("OFF");
        }

        @Override
        public void onCameraSetupForPhoto() {
            mediaActionSwitchView.setText("PHOTO");
            recordButton.setText("TAKE PHOTO");
            flashSwitchView.setVisibility(Component.VISIBLE);
        }

        @Override
        public void onCameraSetupForVideo() {
            mediaActionSwitchView.setText("VIDEO");
            recordButton.setText("CAPTURE VIDEO");
            flashSwitchView.setVisibility(Component.HIDE);
        }

        @Override
        public void onRecordStateVideoReadyForRecord() {
            recordButton.setText("TAKE VIDEO");
        }

        @Override
        public void onRecordStateVideoInProgress() {
            recordButton.setText("STOP");
        }

        @Override
        public void onRecordStatePhoto() {
            recordButton.setText("TAKE PHOTO");
        }

        @Override
        public void onStopVideoRecord() {
            settingsView.setVisibility(Component.VISIBLE);
        }

        @Override
        public void shouldRotateControls(int degrees) {
            cameraSwitchView.setRotation(degrees);
            mediaActionSwitchView.setRotation(degrees);
            flashSwitchView.setRotation(degrees);
        }

        @Override
        public void onStartVideoRecord(File outputFile) {
        }
    }

    /**
     * 接收事件
     *
     * @param busData 接受数据
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void deleteFile(RxBusEvent busData) {
        if (busData == null) {
            return;
        }
        Intent intent = busData.getIntent();
        int intParam = intent.getIntParam(RESPONSE_CODE_ARG, ACTION_RETAKE);
        if (intParam == ACTION_RETAKE || intParam == ACTION_CANCEL) {
            // 删除文件
            eventHandler.postTask(new Runnable() {
                @Override
                public void run() {
                    String absolutePath = getContext().getExternalFilesDir("").getPath();
                    File file = new File(absolutePath);
                    deleteDirectory(file);
                }
            });
        }
    }

    /**
     * 删除图片
     *
     * @param folder 文件
     * @return boolean是否删除
     */
    private boolean deleteDirectory(File folder) {
        if (folder.exists()) {
            File[] files = folder.listFiles();
            if (files == null) {
                return false;
            }
            for (int ii = 0; ii < files.length; ii++) {
                if (files[files.length - 1].getName().startsWith("IMG")) {
                    return files[files.length - 1].delete();
                }
            }
        }
        return folder.delete();
    }
}
